﻿using UnityEngine;
using System;
using System.Linq;
using System.Collections;

namespace Hont.AStar
{
    public class HontAStarUnityDynamicGridItem : MonoBehaviour
    {
        public bool isWalkable;
        public bool defaultWalkableState;
        HontAStarUnity mTargetAStar;
        Position? mOldPosition;


        void Update()
        {
            var useableAStarArr = HontAStarUnity.CreatedAStarList.Where(m => m.IsInitialized);

            var targetAStar = default(HontAStarUnity);
            var isLastAstarContain = mTargetAStar != null && mTargetAStar.LocalBounds.Contains(mTargetAStar.transform.InverseTransformPoint(transform.position));
            if (!isLastAstarContain)
            {
                targetAStar = useableAStarArr.FirstOrDefault(m => m.LocalBounds.Contains(m.transform.InverseTransformPoint(transform.position)));
            }
            else
            {
                targetAStar = mTargetAStar;
            }

            if (targetAStar == null) return;
            if (targetAStar.OctTree == null) return;

            if (targetAStar != mTargetAStar)
                mOldPosition = null;

            mTargetAStar = targetAStar;

            if (mOldPosition.HasValue)
                mTargetAStar.Grid.SetIsWalkable(mOldPosition.Value, defaultWalkableState);

            var pos = mTargetAStar.transform.InverseTransformPoint(transform.position);

            var items = mTargetAStar.OctTree.Root
                .GetItems(m => m.Bounds.Contains(pos) ? -Vector3.Distance(m.Bounds.center, pos) : float.MinValue);

            var target = items == null
                ? null
                : items.FirstOrDefault(m => new Bounds(m.Position, mTargetAStar.MappingSize).Contains(pos));

            if (target != null)
            {
                mTargetAStar.Grid.SetIsWalkable(target.Value, isWalkable);
                mOldPosition = target.Value;
            }
        }
    }
}
